<template>
  <div class="form-container">
    <div class="data-container">
      <el-form :model="addForm" label-width="110px" :rules="addFormRules" ref="addForm">
        <el-form-item  style="width: 300px" label="公司名称" prop="companyName">
          <el-input v-model="addForm.companyName"auto-complete="off" placeholder="请输入公司名"></el-input>
        </el-form-item>
        <el-form-item  style="width: 300px" label="客户姓名" prop="customerName">
          <el-input v-model="addForm.customerName" auto-complete="off" placeholder="请输入客户姓名" disabled></el-input>
        </el-form-item>

        <el-form-item  style="width: 300px" label="联系方式" prop="phoneNumber">
          <el-input v-model="addForm.phoneNumber" auto-complete="off" placeholder="请输入联系方式" @blur="checkCustomer"></el-input>
            <span v-if="showPhoneNumberWarning" class="el-form-item__error">{{ phoneNumberWarningMessage }}</span>
        </el-form-item>
        <el-form-item :label="index === 0 ? '客户电话' : ''" v-for="(telPhone, index) in addForm.telPhone" :key="index" style="width: 330px">
          <el-input v-model="addForm.telPhone[index]" auto-complete="off" placeholder="请输入客户电话" ></el-input>
          <el-button type="text" @click="addInput(index)" v-if="index === addForm.telPhone.length - 1">新增输入框</el-button>
          <el-button type="text" @click="removeInput(index)" v-if="index > 0">移除</el-button>
        </el-form-item>

        <el-form-item style="width: 300px" label="详细地址" prop="address">
          <el-input type="textarea" :rows="2" v-model="addForm.address" auto-complete="off" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item style="width: 300px" label="客户微信" prop="customerWx">
          <el-input v-model="addForm.customerWx" auto-complete="off" placeholder="请输入微信号"></el-input>
        </el-form-item>
        <el-form-item label="客户级别" prop="labelId">
          <el-select v-model="addForm.labelId" placeholder="请选择客户级别">
            <el-option v-for="item in custoLabel"
                       :label="item. customerLabel"
                       :value="item.id">
              <span style="float: left">{{ item. customerLabel }}</span>
              <!--              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>-->
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户销售渠道" prop="typeId">
          <el-select v-model="addForm.typeId" placeholder="请选择客户销售渠道">
            <el-option v-for="item in custoType"
                       :label="item.customerType"
                       :value="item.id">
              <span style="float: left">{{ item.customerType }}</span>
              <!--              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>-->
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户来源" prop="sourceId">
          <el-select v-model="addForm.sourceId" placeholder="请选择客户来源">
            <el-option v-for="item in custoSource"
                       :label="item.customerSource"
                       :value="item.id">
              <span style="float: left">{{ item.customerSource }}</span>
              <!--              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>-->
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="添加图片">
          <el-upload
              class="upload-demo"
              name="file"
              :action="this.$uploadURL"
              :on-remove="handleFileRemove"
              :on-success="handleFileUpload"
              :on-exceed="handleFileExceed"
              :file-list="fileList"
              :limit=5
              :multiple="true"
              accept=".jpg,.png,.gif"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>

          </el-upload>

        </el-form-item>
        <el-form-item style="width: 300px" label="备注信息" prop="notes">
          <el-input type="textarea" :rows="2" v-model="addForm.notes" auto-complete="off" placeholder="请输入备注信息"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">

        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">创建客户</el-button>
      </div>
  </div>
  </div>
</template>
<script>
import util from '../../common/js/util'
export default {
  data() {
    return {
      fileList:[],
      addLoading: false,
      addFormRules: {
        customerName: [
          { required: true, message: '请输入客户名', trigger: 'blur' },
        ],
        companyName: [
          { required: true, message: '请输入公司名称', trigger: 'blur' },
        ],

        typeId: [
          {required: true, message: '请输入客户销售渠道', trigger: 'blur'}
        ],
        address: [
          {required: true, message: '请输入客户详细地址', trigger: 'blur'}
        ],
        phoneNumber: [
          {required: true, message: '请输入联系方式', trigger: 'blur'}
        ],
        labelId: [
          {required: true, message: '请输入客户级别', trigger: 'blur'}
        ],
        sourceId: [
          {required: true, message: '请输入客户来源', trigger: 'blur'}
        ],
      },
      showPhoneNumberWarning: false,
      phoneNumberWarningMessage:'该手机号已存在，请修改',
      //新增界面数据
      addForm: {
        CustomerId: null,
        companyName: '',
        customerName: '',
        phoneNumber: '',
        address: '',
        lastDealTime: '',
        updateTime: '',
        sourceId: '',
        typeId: '',
        labelId: '',
        salesmanId: '',
        customerWx: '',
        distinguish:'',
        picture:[],
        notes:'',
        telPhone: [''],
        entryCustomerTime:'',
      },
      //业务员
      salesMans: [],
      // 客户级别
      custoLabel: [],
      // 客户销售渠道
      custoType: [],
      //客户来源
      custoSource: [],
      serousList:[],
      //重复的客户id
      repeatId:'',
      //新创建的客户id
      newCustomerId:'',

    }
  },

  methods: {
    //新增输入框
    addInput(index) {
      if (this.addForm.telPhone[index].trim() !== '') {
        this.addForm.telPhone.splice(index + 1, 0, '');
      }
    },
//移除当前输入框
    removeInput(index) {
      this.addForm.telPhone.splice(index, 1);
    },
    //输入手机号后做判断
    checkCustomer() {
      const companyName = this.addForm.companyName;
      if (companyName === '') {
        this.$message.info('请先输入公司名称！')
      }
      const phoneNumber = this.addForm.phoneNumber;
      let data = {
        companyName: companyName,
        phone: phoneNumber,
      }
      // 向后端发送查询客户信息的请求
      this.$http.put('/customMycustom/phoneValidation', data).then(response => {
        if (response.data.canAdd=== true) {
          // 后端返回客户存在的情况，弹出提示框
          this.$confirm(`该手机号客户信息已存在，是否跳过创建客户或者修改手机号？`, '提示', {
            confirmButtonText: '跳过创建',
            cancelButtonText: '修改手机号',
            type: 'warning',
          }).then(() => {
            // 用户点击跳过创建的处理逻辑
            this.repeatId=response.data.customerId;
            this.$message({
              type: 'success',
              message: '订单正在创建中，请稍后...',
            });
            this.createOrder();
          }).catch(() => {
            // 用户点击修改手机号的处理逻辑
            this.$message({
              type: 'info',
              message: '请修改手机号',
            },
           );
            this.showPhoneNumberWarning=true
            // 关闭提示框
            this.$refs['confirmDialog'].close();
          });
        } else {
          this.showPhoneNumberWarning = false;

        }
      }).catch(error => {
        console.error('Error checking customer:', error);
      });
    },
    //跳过创建后执行添加订单
    createOrder:function (){
      const orderData = this.$route.params.orderData;
      orderData.customerId = this.repeatId;
      let para=orderData;
      this.$http.put("/orderList/saveOrder", para).then(res => {
        if (res.data.success) {
          this.$message({
            message: '订单创建成功，等待审核中！',
            type: 'success'
          });
          this.repeatId=null;
          //跳转到订单列表中
          // 成功创建订单后跳转到订单审核页面
          this.$router.push({
            path: '/MyOrders',
          });
        } else {
          this.$message.error("系统繁忙，请稍后重试!!!【500】");
        }

      });
    },
    NewCustomercCreateOrder:function (){
      const orderData = this.$route.params.orderData;
      orderData.customerId = this.newCustomerId;
      let para=orderData;
      this.$http.put("/orderList/saveOrder", para).then(res => {
        if (res.data.success) {
          this.$message({
            message: '订单创建成功，等待审核中！',
            type: 'success'
          });
          this.newCustomerId=null;
          // 成功创建订单后跳转到上一个页面
          this.$router.go(-1);

        } else {
          this.$message.error("系统繁忙，请稍后重试!!!【500】");
        }

      });
    },
    //获取类型
    getType() {
      this.$http.get("/customerType").then(res=>{
        this.custoType = res.data;
      })
    },
    //获取业务员
    getSalesman() {
      this.$http.get("/employee").then(res=>{
        this.salesMans = res.data;
      })
    },
    //获取标签
    getLabel() {
      this.$http.get("/customerLabel").then(res=>{
        this.custoLabel = res.data;
      })
    },
    //获取来源
    getSerouce() {
      this.$http.get("/customerSource").then(res=>{
        this. custoSource = res.data;
      })
    },


    //文件删除时的回调
    handleFileRemove(file, fileList) {
      //正式删除
      var fileName = null;
      if (file.response) {  //上传图片的时候点了删除
        fileName = file.response.resultObj;
      } else {  //点击修改回显的图片，点了删除
        fileName = file.url;
      }
      //为了方便参数传递,需要转换路径写法,把/替换为_
      fileName = fileName.replaceAll("/", "_");
      //发送请求
      this.$http.delete("/minio/" + fileName).then(res => {
        if (res.data.success) {
          this.$message.success("删除成功");
          this.fileList = [];
          this.addForm.picture = "";
        } else {
          this.$message.error("删除失败");
        }
      })
    },

    //文件上传成功之后的回调
    handleFileUpload(response) {
      if (response.success) {
        this.addForm.picture.push(response.resultObj);
      }
    },
    //文件上传成功之后的修改页面回调
    handleFileUploadedit(response) {
      if (response.success) {
        this.addForm.picture = response.resultObj;
      }
    },
    //上传超过数量的回调
    handleFileExceed() {
      this.$message.error("不能上传多张图片");
    },

    //6.选项改变时触发
    selsChange: function (sels) {
      this.sels = sels;
    },
    //11.新增
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            const logininfo = JSON.parse(localStorage.getItem("logininfo"));
            const logininfoId = logininfo.id;
            this.addForm.salesmanId=logininfoId;
            this.addForm.entryCustomerTime=new Date();
            let para = Object.assign({}, this.addForm);
            para.picture = para.picture.join(','); // 将标签数组转换为字符串
            para.telPhone = para.telPhone.filter(phone => phone !== '');
            para.telPhone = para.telPhone.join(','); // 将 telPhone 数组转换为字符串
            this.$http.put("/customMycustom/orderToCustomer", para).then(res => {
              if (res.data.success) {
                this.newCustomerId = res.data.resultObj;
                this.NewCustomercCreateOrder();
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['addForm'].resetFields();
              } else {
                this.$message.error("系统繁忙，请稍后重试!!!【500】");
              }
              this.addLoading = false;
            });
          });
        }
      });
    },
  },
  mounted() {
    this.getType();
    this.getLabel();
    this.getSerouce();
    this.getSalesman();
// 获取动态参数 customerName
    const orderData = this.$route.params.orderData;
    if (orderData) {
      // 在这里使用 orderData
      this.addForm.customerName = orderData.customerId;
    }
  }
}

</script>
<style>
.form-container {
  margin-top: 50px;
  margin-left: 10px;
  width: 800px;
  height: 800px;
}
</style>
<style scoped>

</style>